import { useState } from 'react';
import { obj_empty, for_obj } from '../../nui';

const useForm = (setValue) => {
    const [err, setErr] = useState({});

    const hcmd = (k, v) => {
        setValue(old => ({
            ...old,
            [k]: v
        }));
    };

    const hcheck = (ck, value) => {
        if (obj_empty(ck)) {
            return true;
        }

        const error = {};

        for_obj(ck, (k, hck) => {
            if (!hck) {
                return;
            }

            const e = hck(value ? value[k] : null);
            if (e) {
                error[k] = e;
            }
        });

        setErr(error);

        return obj_empty(error);
    };

    const hclear = () => {
        setErr({});
    };

    return {
        err: err,
        hcmd: hcmd,
        hcheck: hcheck,
        hclear: hclear,
    };
};

export {useForm};
